package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.Students.domain.Students;
import com.ruoyi.Students.mapper.StudentsMapper;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.tutors.domain.Tutors;
import com.ruoyi.tutors.mapper.TutorsMapper;
import com.ruoyi.tutors.service.impl.TutorsServiceImpl;
import com.ruoyi.user.domain.Users;
import com.ruoyi.user.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;

/**
 * 数据字典信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dict/data")
public class SysDictDataController extends BaseController
{
    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    @Autowired
    private TutorsMapper tutorsMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private StudentsMapper studentsMapper;

    @PreAuthorize("@ss.hasPermi('system:dict:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysDictData dictData)
    {
        startPage();
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        return getDataTable(list);
    }

    @Log(title = "字典数据", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:dict:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysDictData dictData)
    {
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        ExcelUtil<SysDictData> util = new ExcelUtil<SysDictData>(SysDictData.class);
        util.exportExcel(response, list, "字典数据");
    }

    /**
     * 查询字典数据详细
     */
    @PreAuthorize("@ss.hasPermi('system:dict:query')")
    @GetMapping(value = "/{dictCode}")
    public AjaxResult getInfo(@PathVariable Long dictCode)
    {
        return success(dictDataService.selectDictDataById(dictCode));
    }

    /**
     * 根据字典类型查询字典数据信息
     */
    @GetMapping(value = "/type/{dictType}")
    public AjaxResult dictType(@PathVariable String dictType)
    {

        if(dictType.equals("author")){
            List<Students> studentsList = new ArrayList<>();
            List<Tutors> tutors = new ArrayList<>();

            List<SysDictData> list = new ArrayList<>();

            if ( getLoginUser().getUser().getRemark().equals("学位点")){
                studentsList = studentsMapper.selectList(new QueryWrapper<Students>().eq("point_id",getLoginUser().getUserId()));
                tutors = tutorsMapper.selectList(new QueryWrapper<Tutors>().eq("point_id", getLoginUser().getUserId()));
            }else if (getLoginUser().getUser().getRemark().equals("专家")){
                studentsList = studentsMapper.selectByExpert(getUserId());
                tutors = tutorsMapper.selectByExpert(getUserId());
            }else {
                studentsList = studentsMapper.selectList(null);
                tutors = tutorsMapper.selectList(null);
            }
            Integer count = new Integer(0);

            if(studentsList.size() != 0){
                for (int i = 0; i < studentsList.size(); i++) {
                    list.add(new SysDictData((long) i,(long)i,studentsList.get(i).getStudentName(),count++ +"",dictType,null,"default","N","0"));
                }
            }
            if (tutors.size() != 0){
                for (int i = 0; i < tutors.size(); i++) {
                    list.add(new SysDictData((long) i,(long)i,tutors.get(i).getTutorName(),count++ +"",dictType,null,"default","N","0"));
                }
            }

            return success(list);
        }

        if(dictType.equals("teacher")){
            Tutors tutors1 = new Tutors();
            if(!getLoginUser().getUser().getRemark().equals("专家"))
                tutors1.setPointId(getLoginUser().getUserId());
            List<Tutors> tutors = tutorsMapper.selectTutorsList(tutors1);


            if (tutors.size() == 0){
                return null;
            }
            List<SysDictData> list = new ArrayList<>();
            for (int i = 0; i < tutors.size(); i++) {
                list.add(new SysDictData((long) i,(long)i,tutors.get(i).getTutorName(),tutors.get(i).getTutorId()+"",dictType,null,"default","N","0"));
            }
            DictUtils.setDictCache(dictType, list);
            return success(list);
        }

        if(dictType.equals("expert")){
            List<Users> users = usersMapper.selectUsersList(null);
            if(users.size() == 0){
                return null;
            }
            List<SysDictData> list = new ArrayList<>();
            for (int i = 0; i < users.size(); i++) {
                list.add(new SysDictData((long) i,(long)i,users.get(i).getRealName(),users.get(i).getUserId()+"",dictType,null,"default","N","0"));
            }
            DictUtils.setDictCache(dictType, list);
            return success(list);
        }

        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (StringUtils.isNull(data))
        {
            data = new ArrayList<SysDictData>();
        }
        return success(data);
    }

    /**
     * 新增字典类型
     */
    @PreAuthorize("@ss.hasPermi('system:dict:add')")
    @Log(title = "字典数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDictData dict)
    {
        dict.setCreateBy(getUsername());
        return toAjax(dictDataService.insertDictData(dict));
    }

    /**
     * 修改保存字典类型
     */
    @PreAuthorize("@ss.hasPermi('system:dict:edit')")
    @Log(title = "字典数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDictData dict)
    {
        dict.setUpdateBy(getUsername());
        return toAjax(dictDataService.updateDictData(dict));
    }

    /**
     * 删除字典类型
     */
    @PreAuthorize("@ss.hasPermi('system:dict:remove')")
    @Log(title = "字典类型", businessType = BusinessType.DELETE)
    @DeleteMapping("/{dictCodes}")
    public AjaxResult remove(@PathVariable Long[] dictCodes)
    {
        dictDataService.deleteDictDataByIds(dictCodes);
        return success();
    }
}
